mapVar = {"name": "张三", "age": 28, "gender": "男", "home": "北京"}
# 以默认形式打印
print(json.dumps(mapVar))
# 以美观的形式打印
print("-------------- 以美观的形式打印 --------------")
print(json.dumps(mapVar, indent=True, ensure_ascii=False))
# 当设置True字时，字典对象会按照键的ASCII码来排序
print("-------------- 字典对象会按照键ASCII码来排序  --------------")
print(json.dumps(mapVar, indent=True, ensure_ascii=False, sort_keys=True))

listVar = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 列表转json
print('列表转json:', json.dumps(listVar))
# map 转json
mapVar = {'name': '张三', 'age': 18}
print('map转json:', json.dumps(mapVar))
# ensure_ascii=False 默认为True,如果为False,则汉字不会转义
print('map转json-汉字不转义:', json.dumps(mapVar, ensure_ascii=False))
# 列表map转json
listMapVar = [
    {'name': '张三', 'age': 18},
    {'name': '李四', 'age': 33},
    {'name': '王五', 'age': 20},
]
print('列表map转json:', json.dumps(listMapVar, ensure_ascii=False))

# -------------- 以默认形式打印 --------------
# {"name": "\u5f20\u4e09", "age": 28, "gender": "\u7537", "home": "\u5317\u4eac"}
# -------------- 以美观的形式打印 --------------
# {
#  "name": "张三",
#  "age": 28,
#  "gender": "男",
#  "home": "北京"
# }
# -------------- 字典对象会按照键ASCII码来排序  --------------
# {
#  "age": 28,
#  "gender": "男",
#  "home": "北京",
#  "name": "张三"
# }


# json转列表
listJsonStr = '[1, 2, 3, 4, 5, 6, 7, 8, 9]'
res = json.loads(listJsonStr)
print('json转列表:{} type:{}'.format(res, type(res)))
# json转字典
dictJsonStr = '{"name": "张三", "age": 18}'
res2 = json.loads(dictJsonStr)
print('json转字典:{} type:{}'.format(res2, type(res2)))


class Student:
    def __init__(self, name: str, age: int, phone: str):
        self.name = name
        self.age = age
        self.__phone = phone

    @property
    def tojson(self):
        return {
            'name': self.name,
            'age': self.age,
            'phone': self.__phone
        }
stu = Student("张三", 22, "17600000111")
print("*************** 第一种方式: __dict__ *****************")
print(json.dumps(stu.__dict__, indent=True, ensure_ascii=False))

print("*************** 第二种方式: 自定义方法 *****************")
print(json.dumps(stu.tojson, indent=True, ensure_ascii=False))